﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace SharpDiary.Core.Security
{
    public static class MD5Helper
    {
        static MD5Helper() { }

        /// <summary>
        /// 使用 MD5 加密指定文本。返回十六进制格式字符串。
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string GenerateToMD5HexString(string text)
        {
            if (text == null) { return string.Empty; }

            StringBuilder result = new StringBuilder();

            using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
            {
                byte[] bytes = provider.ComputeHash(System.Text.Encoding.UTF8.GetBytes(text));

                foreach (byte b in bytes)
                {
                    result.Append(b.ToString("x2"));
                }

                return result.ToString();
            }
        }

        /// <summary>
        /// 将 sourceString 作为方法 GenerateMD5HexString 的参数调用，将结果与 MD5String 比较，判断是否相同。（区分大小写）
        /// </summary>
        /// <param name="sourceString">明文</param>
        /// <param name="MD5String">经方法 GenerateMD5HexString 加密的密文</param>
        /// <returns>明文经加密后是否与密文相同（区分大小写）</returns>
        public static bool IsEquals(string sourceString, string MD5String)
        {
            if (sourceString == null) { return false; }

            string encryptedText = GenerateToMD5HexString(sourceString);
            return encryptedText == MD5String;
        }
    }
}
